import * as React from 'react';
import { Service, urlParams } from './services/service';
import { userData } from './services/userData';
// import siteMap from 'user/siteMap';
import { AppError, ErrorCodes, serviceHost } from '../share/common';
import { ShoppingCartService } from './services/shoppingCartService';
import { MemberService, userInfo } from './services/memberService';
import lessc = require('lessc');
// import * as chitu from "maishu-chitu";
import { ImageService, PermissionService } from 'maishu-services-sdk';
import { Page, Application } from 'maishu-chitu-react';
import { createPageUrl } from "maishu-chitu";
import * as ui from "maishu-ui-toolkit";

let { protocol } = location;
ImageService.baseUrl = `${protocol}//${serviceHost}/image`;

window['h'] = window['h'] || React.createElement;

requirejs(['css!components/style/baseStyle']);

// siteMap.nodes["empty"] = {
//     action(page: UserPage) {
//         page.hideLoading();
//     }
// }
PermissionService.baseUrl = "http://127.0.0.1:2856/auth";

export class UserPage extends Page {
    constructor(params) {
        super(params);
        console.assert(this.app instanceof UserApplication);
    }
    get app(): UserApplication {
        return super.app as UserApplication;
    }
}

let link: HTMLLinkElement;

export class UserApplication extends Application {
    constructor(args) {
        super(args);

        this.pageTagName = "article";
        this.pageType = UserPage;
        this.error.add((s, e: AppError, p) => this.on_error(s, e, p as Page));
        this.init();
        if (link == null) {
            link = document.createElement('link');
            link.type = "text/css";
            link.rel = "stylesheet";
            let member = this.createService(MemberService);
            member.store().then(store => {
                let style = store.Style || 'default';
                this.loadStyleCSS(style)
            })

            document.head.appendChild(link);
        }

        this.pageCreated.add((sender, page) => {
            page.element.className = `mobile-page ${page.name}`
        })
    }


    /** 样式颜色 */
    async styleColor(): Promise<StyleColor> {
        let member = this.createService(MemberService);
        let store = await member.store();
        return store.Style;
    }

    /**
     * 加载站点整体的样式文件
     * @param color 颜色
     */
    loadStyleCSS(color: StyleColor) {
        let href = `components/style/style_${color}.css`;
        if (link.href == href) {
            return;
        }
        link.href = href;
    }

    // /** 
    //  * 加载与页面对应的 less 文件 
    //  * @param pageName 页面名称
    //  */
    // async loadPageLess(pageName: string) {
    //     let style = document.head.querySelector(`style[name="${pageName}"]`) as HTMLStyleElement;
    //     if (style) {
    //         return;
    //     }

    //     style = document.createElement('style');
    //     style.type = 'text/css';
    //     style.setAttribute('name', pageName);
    //     document.head.appendChild(style);

    //     let path = pageName.split('_').join('/');
    //     let color = await this.styleColor();
    //     let lessText = `@import "../user/modules/${path}";`;
    //     if (color != 'default') {
    //         lessText = lessText + `@import "components/style/colors/${color}.less";`;
    //     }

    //     let parser = new lessc.Parser(window['less']);
    //     parser.parse(lessText, (err, tree) => {
    //         if (err) {
    //             console.error(err);
    //             return;
    //         }

    //         style.innerHTML = tree.toCSS();
    //     })
    // }

    createUrl(pageName: string, args?: any) {
        let url = createPageUrl(pageName, args);
        return url;
    }

    private static createUrlByPageName(pageName, params) {
        let path_parts = pageName.split('.');
        let path = path_parts.join('/');
        if (!params)
            return `#${path}`;
        let paramsText = '';
        for (let key in params) {
            let value = params[key];
            let type = typeof params[key];
            if (type == 'function' || type == 'object' || value == null) {
                continue;
            }
            paramsText = paramsText == '' ? `?${key}=${params[key]}` : paramsText + `&${key}=${params[key]}`;
        }
        return `#${path}${paramsText}`;
    }

    static createUrl(pageName: string, args?: any) {
        // let pageName: string;
        // if (typeof obj == 'string')
        //     pageName = obj;
        // else {
        //     pageName = obj.name;
        //     console.assert(pageName != null);
        // }

        let url = UserApplication.createUrlByPageName(pageName, args);
        let { protocol, port, host } = location;
        let baseUrl = `${protocol}//${host}/user/?appKey=${urlParams.appKey}`;
        url = baseUrl + url;
        return url;
    }

    // protected createPageElement(pageName: string, containerName: string): HTMLElement {
    //     if (pageName == 'empty')
    //         return this.emtpyPageElement;

    //     let r = this.parseUrl(pageName);
    //     pageName = r.pageName;
    //     debugger
    //     let element = document.createElement(Page.tagName);
    //     element.className = pageName.split('_').join('-') + " mobile-page";
    //     if (location.pathname.endsWith('preview.html')) {
    //         let container = document.querySelector('.screen');
    //         console.assert(container != null, 'screen is not exists.');
    //         container.appendChild(element);
    //     }
    //     else {
    //         document.body.appendChild(element);
    //     }
    //     return element;
    // }

    protected on_error(app: Application, err: AppError, page?: Page) {
        if (err.handled)
            return;

        switch (err.name) {
            case ErrorCodes.Unkonwn:     //600 为未知异常
            default:
                ui.alert({ title: '错误', message: err.message });
                console.log(err);
                break;
            case ErrorCodes.TokenInvalid:     //724 为 token 失效
            case ErrorCodes.UserNotLogin:     //601 为用户未登录异常
                if (err.name == '724') {
                    userData.userToken.value = '';
                }
                // var currentPage = app.currentPage;
                let pageName = page ? page.name : '';
                let isLoginPage = pageName == 'user_login';
                if (isLoginPage) {
                    return;
                }
                //========================================================
                app.forward('user_login', { return: pageName });
                let url = location.href;
                url = url.replace(location.hash, '#user_login');
                break;
            case '725':
                ui.alert({ title: '错误', message: 'application-key 配置错误' });
                break;
        }
    }

    // createService<T extends chitu.Service>(type?: chitu.ServiceConstructor<T>): T {
    //     let service = new type();
    //     service.error.add((sender, err) => {
    //         this.error.fire(this, err, this.currentPage);
    //     })
    //     return service;
    // }

    init() {
        let loadUserInfo = () => {
            let member = this.createService(MemberService);
            member.userInfo().then(data => {
                userInfo.value = data;
            });
        }
        if (Service.loginInfo.value) {
            loadUserInfo();
        }

        Service.loginInfo.add(() => loadUserInfo());

        if (Service.loginInfo.value) {
            let shoppingCart = this.createService(ShoppingCartService);
            shoppingCart.items().then(items => {
                ShoppingCartService.items.value = items;
            });
        }
    }


}




let storeName = localStorage.getItem(`${urlParams.appKey}_storeName`) || '';
ui.loadImageConfig.imageDisaplyText = storeName;



// export function app(): UserApplication {
//     return window["user-app"];
// }



